package anno;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BeanFactory {

    public static Map<String, Object> map = new HashMap<String, Object>();


    public static void main(String[] args) {
        System.out.println(111);

        Person person = (Person) getBean("person");
        System.out.println(person.getPet());
    }

    static {
        try {
            String[] arr = {"anno.Person", "anno.Pet", "anno.Dog", "anno.Cat"};

            for (String beanPath : arr) {
                Class clazz = Class.forName(beanPath);

                Constructor con = clazz.getConstructor();
                con.setAccessible(true);
                Object obj = con.newInstance();
                map.put(clazz.getSimpleName().toLowerCase(), obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 自动装配
    static {
        try {
            Set<Map.Entry<String, Object>> entries = map.entrySet();

            for (Map.Entry<String, Object> entry : entries) {
                Object obj = entry.getValue();
                Class c = obj.getClass();
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (field.isAnnotationPresent(FieldInject.class)) {
                        FieldInject anno = field.getAnnotation(FieldInject.class);
                        String value = anno.value();
                        Object fieldObj = getBean(value.toLowerCase());
                        field.set(obj, fieldObj);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Object getBean(String beanName) {
        return map.get(beanName);
        // 继续做AOP增强
    }

}
